package com.czy.owner.ui.order;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.czy.owner.R;
import com.czy.owner.adapter.BaseRecyclerAdapter;
import com.czy.owner.adapter.OrderAdapter;
import com.czy.owner.adapter.OrderDetailAdapter;
import com.czy.owner.api.OrderInfoApi;
import com.czy.owner.api.UpdateOrderStatusApi;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.OrderInfoDetailModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.rxbus.RxBus;
import com.czy.owner.rxbus.Subscribe;
import com.czy.owner.rxbus.ThreadMode;
import com.czy.owner.rxbus.event.CommonEvent;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.ui.hotshop.GoodsDetailActivity;
import com.czy.owner.ui.hotshop.ShoppingCartActivity;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.TimeUtils;
import com.czy.owner.widget.NoScrollRecyclerView;
import com.czy.owner.widget.UniversalDialog;

import java.io.Serializable;

import butterknife.BindView;

/**
 * Created by wangyang on 2017/6/1 0001.
 * 订单详情
 */

public class OrderDetailActivity extends BaseActivity {
    @BindView(R.id.tv_order_top_status)
    TextView tvOrderTopStatus;
    @BindView(R.id.tv_order_top_time)
    TextView tvOrderTopTime;
    @BindView(R.id.img_order_detail_status)
    ImageView imgOrderDetailStatus;
    @BindView(R.id.tv_receiver_people)
    TextView tvReceiverPeople;
    @BindView(R.id.tv_receiver_people_phone)
    TextView tvReceiverPeoplePhone;
    @BindView(R.id.tv_receiver_people_address)
    TextView tvReceiverPeopleAddress;
    @BindView(R.id.tv_store_name)
    TextView tvStoreName;
    @BindView(R.id.tv_pay_status)
    TextView tvPayStatus;
    @BindView(R.id.recycleview)
    NoScrollRecyclerView recycleView;
    @BindView(R.id.tv_order_detail_install_money)
    TextView tvOrderDetailInstallMoney;
    @BindView(R.id.rl_order_detail_install_money)
    RelativeLayout rlOrderDetailInstallMoney;
    @BindView(R.id.tv_order_detail_discount)
    TextView tvOrderDetailDiscount;
    @BindView(R.id.rl_order_detail_discount)
    RelativeLayout rlOrderDetailDiscount;
    @BindView(R.id.tv_order_detail_freight)
    TextView tvOrderDetailFreight;
    @BindView(R.id.tv_order_detail_actual_payment)
    TextView tvOrderDetailActualPayment;
    @BindView(R.id.tv_growth_value)
    TextView tvGrowthValue;
    @BindView(R.id.tv_order_detail_number)
    TextView tvOrderDetailNumber;
    @BindView(R.id.tv_order_detail_account)
    TextView tvOrderDetailAccount;
    @BindView(R.id.tv_order_detail_create_time)
    TextView tvOrderDetailCreateTime;
    @BindView(R.id.tv_order_detail_pay_time)
    TextView tvOrderDetailPayTime;
    @BindView(R.id.tv_order_detail_delivery_time)
    TextView tvOrderDetailDeliveryTime;
    @BindView(R.id.tv_order_detail_receiver_time)
    TextView tvOrderDetailReceiverTime;
    @BindView(R.id.tv_order_detail_install_time)
    TextView tvOrderDetailInstallTime;
    @BindView(R.id.tv_order_detail_evaluate_time)
    TextView tvOrderDetailEvaluateTime;
    @BindView(R.id.tv_order_detail_cancel_time)
    TextView tvOrderDetailCancelTime;
    @BindView(R.id.tv_bottom_order_left)
    TextView tvBottomOrderLeft;
    @BindView(R.id.tv_bottom_order_center)
    TextView tvBottomOrderCenter;
    @BindView(R.id.tv_bottom_order_right)
    TextView tvBottomOrderRight;


    //    2018-2-2新增
    @BindView(R.id.rl_order_detail_member_price)
    RelativeLayout rlOrderDetailMemberPrice;
    @BindView(R.id.tv_goods_member_discount)
    TextView tvGoodsMemberDiscount;//会员价


    private int orderId;
    private OrderDetailAdapter adapter;
    private double detailActualPayment; //实付款
    private String mOrderStatus;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_order_detail;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText(R.string.person_my_order_detail);
        RxBus.getDefault().register(this);
        orderId = getIntent().getIntExtra("orderId", 0);
        if (orderId == 0) {
            finish();
            PhoneUtils.ShowToastMessage(OrderDetailActivity.this, "参数错误");
            return;
        }

        getData();


    }

    @Override
    protected void updateViews() {

    }


    private void getData() {
        OrderInfoApi orderInfoApi = new OrderInfoApi(new HttpOnNextListener<OrderInfoDetailModel>() {
            @Override
            public void onNext(final OrderInfoDetailModel model) {
                // 会员优惠
                double sumMemberDiscount = 0;
                for (int i = 0; i < model.getOrderItems().size(); i++) {
                    sumMemberDiscount += (model.getOrderItems().get(i).getOriginalPrice() * model.getOrderItems().get(i).getCount() - model.getOrderItems().get(i).getPrice() * model.getOrderItems().get(i).getCount());
                }

                if (sumMemberDiscount != 0 && sumMemberDiscount>0) {
                    rlOrderDetailMemberPrice.setVisibility(View.VISIBLE);
                    tvGoodsMemberDiscount.setText("-￥" + String.format("%.2f", sumMemberDiscount));
                } else {
                    rlOrderDetailMemberPrice.setVisibility(View.GONE);
                }



                // waitPay：待付款，waitDelivery：待发货，delivery：已发货，toInstall：待安装，completed：已完成，commented：已评价，cancelled：已取消
                String orderStatus = model.getOrderStatus();
                mOrderStatus = orderStatus;
                final int orderId = model.getUserOrderId();
                final long day = model.getDay();
                if (orderStatus.equals("waitPay")) {
                    tvOrderTopStatus.setText("等待买家付款");
//                    tvPayStatus.setText("等待买家付款");
                    myDay(day, "自动关闭");
                    imgOrderDetailStatus.setImageResource(R.mipmap.icon_order_detail_stay_payment);
                    tvOrderDetailDeliveryTime.setVisibility(View.GONE);
                    tvBottomOrderRight.setVisibility(View.VISIBLE);
                    tvBottomOrderRight.setText("付款");
                    tvBottomOrderCenter.setText("取消订单");
                    tvBottomOrderLeft.setVisibility(View.VISIBLE);
                    if (model.getStoreId() != 0) {
                        if (model.getFromGoodsId() != 0) {
                            tvBottomOrderLeft.setText("联系客服");
                        } else {
                            tvBottomOrderLeft.setText("联系卖家");
                        }
                    } else {
                        tvBottomOrderLeft.setText("联系客服");
                    }
                    tvOrderDetailReceiverTime.setVisibility(View.GONE);
                    tvOrderDetailPayTime.setVisibility(View.GONE);
                } else if (orderStatus.equals("waitDelivery")) {
                    tvOrderTopStatus.setText("等待卖家发货");
//                    tvPayStatus.setText("等待卖家发货");
//                    myDay(day, "自动关闭");
                    imgOrderDetailStatus.setImageResource(R.mipmap.icon_order_detail_delivery);
                    tvBottomOrderRight.setVisibility(View.GONE);

                    if (model.getStoreId() != 0) {
                        if (model.getFromGoodsId() != 0) {
                            tvBottomOrderCenter.setText("联系客服");
                        } else {
                            tvBottomOrderCenter.setText("联系卖家");
                        }
                    } else {
                        tvBottomOrderCenter.setText("联系客服");
                    }
                    tvBottomOrderLeft.setVisibility(View.GONE);
                    tvOrderDetailDeliveryTime.setVisibility(View.GONE);
                    tvOrderDetailReceiverTime.setVisibility(View.GONE);
                    tvOrderDetailPayTime.setVisibility(View.VISIBLE);
                } else if (orderStatus.equals("delivery")) {
                    tvOrderTopStatus.setText("卖家已发货");
//                    tvPayStatus.setText("卖家已发货");
                    myDay(day, "自动确认");
                    imgOrderDetailStatus.setImageResource(R.mipmap.icon_order_detail_delivery);
                    tvBottomOrderRight.setVisibility(View.VISIBLE);
                    tvBottomOrderRight.setText("确认收货");
                    if(model.getIsShippingToStore().equals("true")){
                        tvBottomOrderCenter.setVisibility(View.GONE);
                    }else {
                        tvBottomOrderCenter.setVisibility(View.VISIBLE);
                    }
                    tvBottomOrderCenter.setText("查看物流");
                    tvBottomOrderLeft.setVisibility(View.GONE);
                    tvOrderDetailReceiverTime.setVisibility(View.GONE);
                    tvOrderDetailPayTime.setVisibility(View.VISIBLE);
                } else if (orderStatus.equals("toInstall")) {
                    tvOrderTopStatus.setText("买家已收货");
//                    tvPayStatus.setText("待安装");
                    myDay(day, "自动确认安装");
                    imgOrderDetailStatus.setImageResource(R.mipmap.icon_order_detail_toinstall);
                    tvBottomOrderRight.setVisibility(View.VISIBLE);
                    tvBottomOrderRight.setText("确认安装");
                    if(model.getIsShippingToStore().equals("true")){
                        tvBottomOrderCenter.setVisibility(View.GONE);
                    }else {
                        tvBottomOrderCenter.setVisibility(View.VISIBLE);
                    }
                    tvBottomOrderCenter.setText("查看物流");
                    tvBottomOrderLeft.setVisibility(View.GONE);
                } else if (orderStatus.equals("completed")) {
                    imgOrderDetailStatus.setImageResource(R.mipmap.icon_order_detail_install);
                    tvBottomOrderRight.setVisibility(View.GONE);
                    tvBottomOrderCenter.setText("去评价");
                    tvBottomOrderLeft.setVisibility(View.GONE);

                    if (model.getInstallTime() != 0) {
                        tvOrderDetailInstallTime.setVisibility(View.VISIBLE);
                        tvOrderDetailInstallTime.setText("安装时间:  " + TimeUtils.formatTimeDifference(model.getInstallTime()));
                        tvOrderTopStatus.setText("卖家已安装");
                        tvOrderTopTime.setText("安装已完成,服务还满意吗");
                    } else {
                        tvOrderTopStatus.setText("订单已完成");
                        tvOrderTopTime.setText("订单已完成,服务还满意吗");

                    }
                    tvOrderDetailPayTime.setVisibility(View.VISIBLE);

                } else if (orderStatus.equals("commented")) {
                    tvOrderTopStatus.setText("买家已评价");
                    tvBottomOrderRight.setVisibility(View.GONE);
                    tvBottomOrderCenter.setText("查看评价");
                    tvBottomOrderLeft.setVisibility(View.GONE);
                    imgOrderDetailStatus.setImageResource(R.mipmap.icon_order_detail_install);
                    if (model.getInstallTime() != 0) {
                        tvOrderDetailInstallTime.setVisibility(View.VISIBLE);
                        tvOrderDetailInstallTime.setText("安装时间:  " + TimeUtils.formatTimeDifference(model.getInstallTime()));
                    }

                    if (model.getCommentTime() != 0) {
                        tvOrderDetailEvaluateTime.setVisibility(View.VISIBLE);
                        tvOrderDetailEvaluateTime.setText("评价时间:  " + TimeUtils.formatTimeDifference(model.getCommentTime()));
                    }
                    tvOrderDetailPayTime.setVisibility(View.VISIBLE);
                } else if (orderStatus.equals("cancelled")) {
                    MyLog.e("yang", "cancelled");
                    tvOrderTopStatus.setText("已取消");
                    tvBottomOrderRight.setVisibility(View.GONE);
                    tvBottomOrderCenter.setText("删除订单");
                    tvBottomOrderLeft.setVisibility(View.GONE);
//                    tvPayStatus.setText("已取消");
//                    myDay(day, "自动确认安装");
                    imgOrderDetailStatus.setImageResource(R.mipmap.icon_order_detail_toinstall);
                    if (model.getPayStatus().equals("alreadyPay")) {
                        tvOrderDetailDeliveryTime.setVisibility(View.VISIBLE);
                        if (model.getReceivingTime() != 0) {
                            tvOrderDetailReceiverTime.setVisibility(View.VISIBLE);
                        } else {
                            tvOrderDetailReceiverTime.setVisibility(View.GONE);
                        }
                        tvOrderDetailPayTime.setVisibility(View.VISIBLE);
                    } else {
                        tvOrderDetailDeliveryTime.setVisibility(View.GONE);
                        tvOrderDetailReceiverTime.setVisibility(View.GONE);
                        tvOrderDetailPayTime.setVisibility(View.GONE);
                    }


                    tvOrderDetailCancelTime.setVisibility(View.VISIBLE);
                    tvOrderDetailCancelTime.setText("取消时间:  " + TimeUtils.formatTimeDifference(model.getCancelTime()));
                }

                tvReceiverPeople.setText("收货人:" + model.getShippingAddressName());
                tvReceiverPeoplePhone.setText(model.getShippingAddressContact());
                tvReceiverPeopleAddress.setText(model.getShippingAddress());

//                运费
                tvOrderDetailFreight.setText("￥" + String.format("%.2f", model.getFreight()));

                double discountPrice = 0.00;
                // 优惠金额
                if (model.getOrderItems().size() > 0) {
                    for (int i = 0; i < model.getOrderItems().size(); i++) {
                        discountPrice += model.getOrderItems().get(i).getDiscountPrice();
                    }

                }

                double denomination = model.getDenomination();


                tvOrderDetailDiscount.setText("-￥" + String.format("%.2f", discountPrice));

                //                安装费
                double servicePrice = 0.00;
                if (model.getOrderItems().size() > 0) {
                    for (int i = 0; i < model.getOrderItems().size(); i++) {
                        servicePrice += model.getOrderItems().get(i).getServicePrice();
                    }
                }

                tvOrderDetailInstallMoney.setText("￥" + String.format("%.2f", servicePrice));

                // 实付款=商品总额+运费+安装费-优惠券金额
                detailActualPayment = model.getTotal() + model.getFreight() + servicePrice - discountPrice;
                tvOrderDetailActualPayment.setText("￥" + String.format("%.2f", detailActualPayment));
                MyLog.e("yang", "model.getTotal()==" + model.getTotal());
                MyLog.e("yang", "model.getFreight()==" + model.getFreight());
                MyLog.e("yang", "servicePrice==" + servicePrice);
                MyLog.e("yang", "denomination==" + discountPrice);


                tvOrderDetailNumber.setText("订单编号:  " + model.getOrderNumber());
                //tvOrderDetailAccount.setText("支付交易账户:  732392893833");
                tvOrderDetailCreateTime.setText("创建时间:  " + TimeUtils.formatTimeDifference(model.getCreateTime()));
                tvOrderDetailPayTime.setText("付款时间:  " + TimeUtils.formatTimeDifference(model.getPayTime()));
                MyLog.e("yang", "model.getPayTime()==" + model.getPayTime());
                long mShipTime = 0;
                for (int i = 0; i < model.getOrderItems().size(); i++) {
                    long shipTime = model.getOrderItems().get(i).getShipTime();
                    if (shipTime > mShipTime) {
                        mShipTime = shipTime;
                    }
                }
                if (mShipTime != 0) {
                    tvOrderDetailDeliveryTime.setVisibility(View.VISIBLE);
                } else {
                    tvOrderDetailDeliveryTime.setVisibility(View.GONE);
                }
                tvOrderDetailDeliveryTime.setText("发货时间:  " + TimeUtils.formatTimeDifference(mShipTime));
                tvOrderDetailReceiverTime.setText("收货时间:  " + TimeUtils.formatTimeDifference(model.getReceivingTime()));

                if (model.getStoreId() != 0) {
                    if (model.getFromGoodsId() != 0) {
                        tvStoreName.setText("平台转移");
                    } else {
                        tvStoreName.setText(model.getStoreName());
                    }
                } else {
                    tvStoreName.setText("平台自营");
                }

                adapter = new OrderDetailAdapter(OrderDetailActivity.this, model.getOrderItems(), model.getOrderStatus(), model.getOrderSubType(), model.getNowTime(), model.getPayTime());
                recycleView.setLayoutManager(new LinearLayoutManager(OrderDetailActivity.this));
                recycleView.addItemDecoration(new RecycleViewDivider(OrderDetailActivity.this, LinearLayoutManager.VERTICAL, R.drawable.shape_recyclerview_divider_decoration));
                recycleView.setAdapter(adapter);
                adapter.setList(model.getOrderItems());


                adapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<OrderInfoDetailModel.OrderItemsBean>() {
                    @Override
                    public void onItemClick(int position, OrderInfoDetailModel.OrderItemsBean data, View view) {
                        Intent intent = new Intent(OrderDetailActivity.this, GoodsDetailActivity.class);
                        intent.putExtra("goodsId", Integer.parseInt(data.getItemTypeId()));
                        intent.putExtra("mFromType", Constants.GOODSSOURCE_OTHER);
                        intent.putExtra("mFromTypeId", "0");
                        startActivity(intent);
                    }
                });


                adapter.setOnItemReturnOrderListener(new OrderDetailAdapter.OnItemReturnOrderListener() {
                    @Override
                    public void onSet(OrderInfoDetailModel.OrderItemsBean data, int position) {
                        Intent ti = new Intent(OrderDetailActivity.this, RefundActivity.class);
                        ti.putExtra("isEdit", false);
                        ti.putExtra("userOrderId", orderId);
                        ti.putExtra("goodsId", data.getItemTypeId());
                        ti.putExtra("specGroupKey", data.getSpecGroupKey());
                        ti.putExtra("refundTitle", "申请退款");

                        // waitPay：待付款，waitDelivery：待发货，delivery：已发货，toInstall：待安装，completed：已完成，commented：已评价，cancelled：已取消

                        double price = data.getPrice() * data.getCount();
                        double freight = data.getFreight();
                        double servicePrice = data.getServicePrice();
                        double discountPrice = data.getDiscountPrice();
                        //待发货 可退商品+运费+安装费(如果有)
                        if (mOrderStatus.equals("waitDelivery") && data.getNeedService().equals("true")) {
                            ti.putExtra("applyRefundsAmount", price + freight + servicePrice - discountPrice);
                            MyLog.e("yang", "qqqqqqq===" + (price + freight + servicePrice - discountPrice));
                        } else if (mOrderStatus.equals("waitDelivery")) {
                            ti.putExtra("applyRefundsAmount", price + freight - discountPrice);
                            MyLog.e("yang", "wwwww===" + (price + freight - discountPrice));
                            MyLog.e("yang", "price===" + price + "\nfreight==" + freight + "\ndiscountPrice" + discountPrice);
                            //待收货-- 可退商品+安装费(如果有)，不可退运费
                        } else if (mOrderStatus.equals("delivery") && data.getNeedService().equals("true")) {
                            ti.putExtra("applyRefundsAmount", price + servicePrice - discountPrice);
                        } else if (mOrderStatus.equals("delivery")) {
                            ti.putExtra("applyRefundsAmount", price - discountPrice);
                        }
                        //待安装--可退款/退货-可退商品+安装费，不可退运费
                        else if (mOrderStatus.equals("toInstall") && data.getNeedService().equals("true")) {
                            ti.putExtra("applyRefundsAmount", price + servicePrice - discountPrice);
                        } else if (mOrderStatus.equals("toInstall")) {
                            ti.putExtra("applyRefundsAmount", price - discountPrice);
                        } //待评价--已安装的--无退款/退货按钮， 无安装的--可退款/退货，只能退商
                        else if (mOrderStatus.equals("completed") && data.getNeedService().equals("true")) {
                            ti.putExtra("applyRefundsAmount", price + servicePrice - discountPrice);
                        } else if (mOrderStatus.equals("completed")) {
                            MyLog.e("yang", "qqqqqqqqqqqq==" + price);
                            MyLog.e("yang", "wwwwwwwwwww==" + discountPrice);
                            ti.putExtra("applyRefundsAmount", price - discountPrice);
                        } else {
                            ti.putExtra("applyRefundsAmount", price - discountPrice);
                        }

                        ti.putExtra("orderStatus", mOrderStatus);
                        ti.putExtra("orderItemId", data.getOrderItemId());
                        startActivity(ti);
                    }
                });


                tvBottomOrderRight.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        switch (getOrderStatusType(model)) {
                            case WAITPAY:
                                Intent ti = new Intent(OrderDetailActivity.this, OrderPaidActivity.class);
                                ti.putExtra("storeId", model.getStoreId());
                                ti.putExtra("totalPrice", detailActualPayment);
                                ti.putExtra("orderNumber", model.getOrderNumber());
                                ti.putExtra("name", model.getShippingAddressName());
                                ti.putExtra("contact", model.getShippingAddressContact());
                                ti.putExtra("address", model.getShippingAddress());
                                ti.putExtra("orderType", model.getOrderSubType());
                                startActivity(ti);


                                break;
                            case DELIVERY:
                                String msg = "是否确定收货?";
                                for (int i = 0; i < model.getOrderItems().size(); i++) {
                                    if (model.getOrderItems().get(i).getIsRefund().equals("true") && !model.getOrderItems().get(i).getRefundsStatus().equals("complete")) {
                                        msg = "该订单存在退款记录的宝贝,确认收货将关闭退款。";
                                        break;
                                    }
                                }

                                new UniversalDialog(OrderDetailActivity.this).builder().setTitle("温馨提示")
                                        .setMsg(msg)
                                        .setPositiveButton("确定", new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                updateOrderStatus("receipt", orderId + "");
                                            }
                                        }).setNegativeButton("取消", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {

                                    }
                                }).show();

                                break;
                            case TOINSTALL:
                                String msg2 = "是否确定安装?";
                                for (int i = 0; i < model.getOrderItems().size(); i++) {
                                    if (model.getOrderItems().get(i).getIsRefund().equals("true") && !model.getOrderItems().get(i).getRefundsStatus().equals("complete")) {
                                        msg2 = "该订单存在退款记录的宝贝,确认安装将关闭退款。";
                                        break;
                                    }
                                }
                                new UniversalDialog(OrderDetailActivity.this).builder().setTitle("温馨提示")
                                        .setMsg(msg2)
                                        .setPositiveButton("确定", new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                updateOrderStatus("install", orderId + "");
                                            }
                                        }).setNegativeButton("取消", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {

                                    }
                                }).show();

                                break;
                        }
                    }
                });
                tvBottomOrderCenter.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        switch (getOrderStatusType(model)) {
                            case WAITPAY:
                                new UniversalDialog(OrderDetailActivity.this).builder().setTitle("取消订单")
                                        .setMsg("确定取消该订单吗?取消后不可恢复")
                                        .setPositiveButton("确定", new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                updateOrderStatus("cancel", orderId + "");

                                            }
                                        }).setNegativeButton("取消", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {

                                    }
                                }).show();

                                break;
                            case WAITDELIVERY:
//                                if (model.getStoreId() != 0) {
//                                    PhoneUtils.ShowToastMessage(OrderDetailActivity.this, "联系卖家");
//                                } else {
//                                    PhoneUtils.ShowToastMessage(OrderDetailActivity.this, "联系客服");
//                                }
                                OrderAdapter.pushGoods(OrderDetailActivity.this, model.getStoreId(), model.getUserOrderId(), model.getFromGoodsId(), (model.getOrderItems() != null && model.getOrderItems().size() > 0) ? Integer.parseInt(model.getOrderItems().get(0).getItemTypeId()) : model.getFromGoodsId(), model.getOrderItems().get(0).getPrice() + "", model.getOrderItems().get(0).getLogo());
                                break;
                            case DELIVERY:
                                StringBuffer sbName = new StringBuffer();
                                StringBuffer sbNumber = new StringBuffer();
                                StringBuffer sbGoodIds = new StringBuffer();
                                if (model.getOrderItems().size() > 0) {
                                    for (int i = 0; i < model.getOrderItems().size(); i++) {
                                        sbName.append(model.getOrderItems().get(i).getLogisticsCompany() + ",");
                                        sbNumber.append(model.getOrderItems().get(i).getLogisticsNumber() + ",");
                                        sbGoodIds.append(model.getOrderItems().get(i).getOrderItemId() + ",");

                                    }
                                }
                                Intent tiLogistics1 = new Intent(OrderDetailActivity.this, LogisticsActivity.class);
                                tiLogistics1.putExtra("userOrderId", model.getUserOrderId());
//                                tiLogistics1.putExtra("name", sbName.toString());
//                                tiLogistics1.putExtra("number", sbNumber.toString());
//                                tiLogistics1.putExtra("goodsIds", sbGoodIds.toString());
                                startActivity(tiLogistics1);
                                break;
                            case TOINSTALL:
                                StringBuffer sbName2 = new StringBuffer();
                                StringBuffer sbNumber2 = new StringBuffer();
                                StringBuffer sbGoodIds2 = new StringBuffer();
                                if (model.getOrderItems().size() > 0) {
                                    for (int i = 0; i < model.getOrderItems().size(); i++) {
                                        sbName2.append(model.getOrderItems().get(i).getLogisticsCompany() + ",");
                                        sbNumber2.append(model.getOrderItems().get(i).getLogisticsNumber() + ",");
                                        sbGoodIds2.append(model.getOrderItems().get(i).getOrderItemId() + ",");
                                    }
                                }
                                Intent tiLogistics2 = new Intent(OrderDetailActivity.this, LogisticsActivity.class);
                                tiLogistics2.putExtra("userOrderId", model.getUserOrderId());
//                                tiLogistics2.putExtra("name", sbName2.toString());
//                                tiLogistics2.putExtra("number", sbNumber2.toString());
//                                tiLogistics2.putExtra("goodsIds", sbGoodIds2.toString());
                                startActivity(tiLogistics2);
                                break;
                            case COMPLETED:
                                String msg3 = "";
                                for (int i = 0; i < model.getOrderItems().size(); i++) {
                                    if (model.getOrderItems().get(i).getIsRefund().equals("true") && !model.getOrderItems().get(i).getRefundsStatus().equals("complete")) {
                                        msg3 = "该订单存在退款记录的宝贝,确认评价将关闭退款。";
                                        break;
                                    }
                                }
                                if (TextUtils.isEmpty(msg3)) {
                                    Intent ti = new Intent(OrderDetailActivity.this, EvaluateActivity.class);
                                    ti.putExtra("isFromDetail", true);
                                    ti.putExtra("orderItemsDetail", (Serializable) model.getOrderItems());
                                    ti.putExtra("userOrderId", model.getUserOrderId());
                                    startActivity(ti);
                                } else {
                                    new UniversalDialog(OrderDetailActivity.this).builder().setTitle("温馨提示")
                                            .setMsg(msg3)
                                            .setPositiveButton("确定", new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {
                                                    Intent ti = new Intent(OrderDetailActivity.this, EvaluateActivity.class);
                                                    ti.putExtra("isFromDetail", true);
                                                    ti.putExtra("orderItemsDetail", (Serializable) model.getOrderItems());
                                                    ti.putExtra("userOrderId", model.getUserOrderId());
                                                    startActivity(ti);
                                                }
                                            }).setNegativeButton("取消", new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {

                                        }
                                    }).show();
                                }


                                break;
                            case COMMENTED:
                                Intent ti2 = new Intent(OrderDetailActivity.this, SeeEvaluateActivity.class);
                                ti2.putExtra("userOrderId", model.getUserOrderId());
                                startActivity(ti2);
                                break;
                            case CANCELLED:
                                new UniversalDialog(OrderDetailActivity.this).builder().setTitle("删除订单")
                                        .setMsg("确定删除该订单吗?删除后不可恢复")
                                        .setPositiveButton("确定", new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                updateOrderStatus("del", orderId + "");
                                            }
                                        }).setNegativeButton("取消", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {

                                    }
                                }).show();

                                break;
                        }

                    }
                });
                tvBottomOrderLeft.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        switch (getOrderStatusType(model)) {
                            case WAITPAY:
                                OrderAdapter.pushGoods(OrderDetailActivity.this, model.getStoreId(), model.getUserOrderId(), model.getFromGoodsId(), (model.getOrderItems() != null && model.getOrderItems().size() > 0) ? Integer.parseInt(model.getOrderItems().get(0).getItemTypeId()) : model.getFromGoodsId(), model.getOrderItems().get(0).getPrice() + "", model.getOrderItems().get(0).getLogo());
                                // PhoneUtils.ShowToastMessage(OrderDetailActivity.this, "联系卖家");
                                break;

                        }

                    }
                });


            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
            }
        }, this);
        orderInfoApi.setSession(UserHelper.getInstance().getSessionInfoModel(OrderDetailActivity.this).getSession());
        orderInfoApi.setOrderId(orderId + "");
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(orderInfoApi);
    }


    private void myDay(long day, String status) {
        if (day == 0) {
            tvOrderTopTime.setText("已关闭");
        } else {
            tvOrderTopTime.setText("剩" + TimeUtils.getFitTimeSpan(day, 0, 3) + status);
        }
    }

    //type 更改订单状态类型 cancel:撤销订单，receipt：确认收货，install：确认安装，del:删除订单
    private void updateOrderStatus(final String type, String orderId) {
        UpdateOrderStatusApi updateOrderStatusApi = new UpdateOrderStatusApi(new HttpOnNextListener<Double>() {
            @Override
            public void onNext(Double data) {
                // {0:不需要安装，1:需要安装},
                if (type.equals("del")) {
                    Intent intent = new Intent();
                    intent.setAction(OrderActivity.orderAction);
                    intent.putExtra("currentId", OrderActivity.currentId);
                    sendBroadcast(intent);
                } else if (type.equals("cancel")) {
                    Intent intent = new Intent();
                    intent.setAction(OrderActivity.orderAction);
                    intent.putExtra("currentId", 0);
                    sendBroadcast(intent);
                } else if (type.equals("receipt")) {
                    Intent intent = new Intent();
                    intent.setAction(OrderActivity.orderAction);
                    if (data == 1) {
                        intent.putExtra("currentId", 3);
                    } else {
                        intent.putExtra("currentId", 4);
                    }
                    sendBroadcast(intent);
                } else if (type.equals("install")) {
                    Intent intent = new Intent();
                    intent.setAction(OrderActivity.orderAction);
                    intent.putExtra("currentId", 4);
                    sendBroadcast(intent);
                }
                finish();
            }


            @Override
            public void onError(Throwable e) {
                super.onError(e);
                e.printStackTrace();
                MyLog.e("yang", e.getMessage());
                PhoneUtils.ShowToastMessage(OrderDetailActivity.this, e.getMessage());
            }
        }, OrderDetailActivity.this);
        updateOrderStatusApi.setSession(UserHelper.getInstance().getSessionInfoModel(OrderDetailActivity.this).getSession());
        updateOrderStatusApi.setType(type);
        updateOrderStatusApi.setOrderId(orderId);
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(updateOrderStatusApi);
    }


    // waitPay：待付款，waitDelivery：待发货，delivery：已发货，toInstall：待安装，completed：已完成，commented：已评价，cancelled：已取消
    private static final int WAITPAY = 1;
    private static final int WAITDELIVERY = 2;
    private static final int DELIVERY = 3;
    private static final int TOINSTALL = 4;
    private static final int COMPLETED = 5;
    private static final int COMMENTED = 6;
    private static final int CANCELLED = 7;
    private static final int DEFAULT = 0;

    private int getOrderStatusType(OrderInfoDetailModel data) {
        if (data.getOrderStatus().equals("waitPay")) {
            return WAITPAY;
        } else if (data.getOrderStatus().equals("waitDelivery")) {
            return WAITDELIVERY;
        } else if (data.getOrderStatus().equals("delivery")) {
            return DELIVERY;
        } else if (data.getOrderStatus().equals("toInstall")) {
            return TOINSTALL;
        } else if (data.getOrderStatus().equals("completed")) {
            return COMPLETED;
        } else if (data.getOrderStatus().equals("commented")) {
            return COMMENTED;
        } else if (data.getOrderStatus().equals("cancelled")) {
            return CANCELLED;
        } else {
            return DEFAULT;
        }
    }

    @Subscribe(code = Constants.ORDER_PAYMENT_SECCESS_CODE, threadMode = ThreadMode.MAIN)
    public void onPaymentSuccess(CommonEvent event) {
        finish();
    }

    @Subscribe(code = Constants.ORDER_EVALUATE_SECCESS_CODE, threadMode = ThreadMode.MAIN)
    public void onEvaluateSuccess(CommonEvent event) {
        finish();
    }


    @Subscribe(code = Constants.RETURNORDER, threadMode = ThreadMode.MAIN)
    public void onReturnSuccess(CommonEvent event) {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unRegister(this);
    }


}
